import { defineStore } from 'pinia';
import { request } from '@/utils/request';

interface IUserState {
  token: string | null;
  userInfo: Record<string, any> | null;
  isAuthenticated: boolean;
  roles: string[];
}

export const useUserStore = defineStore('user', {
  state: (): IUserState => ({
    token: localStorage.getItem('token') || null,
    userInfo: null,
    isAuthenticated: false,
    roles: [],
  }),

  getters: {
    isLoggedIn: state => !!state.token,
    userName: state => state.userInfo?.name || 'Guest',
  },

  actions: {
    // 登录操作
    async login(username: string, password: string) {
      const res = await request<any>(`/login`, { method: 'POST', data: { username, password } });
      this.token = res.data;
      this.isAuthenticated = true;
      localStorage.setItem('token', res.data);
    },

    // 获取用户信息
    async fetchUserInfo() {
      if (!this.token) return;
      const res = await request<any>(`/userinfo`);
      this.userInfo = res.data;
      this.roles = res.data.roles;
    },

    // 退出登录
    logout() {
      this.token = null;
      this.userInfo = null;
      this.isAuthenticated = false;
      localStorage.removeItem('token');
    },
  },
});
